import { FormSchema } from '/@/components/Form/index';
import { Button } from '/@/components/Button';
import { UseFormReturnType, useForm, FormProps } from '/@/components/Form';
import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
import { useMessage } from '/@/hooks/web/useMessage';
import { Icon } from '/@/components/Icon';
import { getDeviceProfileInfos, getCustomerList } from '/@/api/thingsborad/entity/entity';
import { modalFormStyleSetting } from '/@/settings/thingsBoardDesign';
import { ref } from 'vue';
import { useDebounceFn } from '@vueuse/core';
export function generate(length?: number): string {
  if (Boolean(typeof length == 'undefined') || length == null) {
    length = 1;
  }
  const l = length > 10 ? 10 : length;
  const str = Math.random().toString(36).substr(2, l);
  if (str.length >= length) {
    return str;
  }
  return str.concat(generate(length - str.length));
}

export const schemas: FormSchema[] = [
  {
    field: 'name',
    component: 'Input',
    label: '名称',
    colProps: {
      span: 12,
    },
    componentProps: {
      placeholder: '请输入名称',
    },
    required: true,
  },
  {
    field: 'label',
    component: 'Input',
    label: '标签',
    componentProps: {
      placeholder: '请输入标签',
    },
    colProps: {
      span: 12,
    },
  },
  {
    field: 'deviceConfiguration',
    component: 'ApiSelect',
    label: '设备配置',
    componentProps: () => {
      const params = ref({
        page: 0,
        pageSize: 10,
        textSearch: '',
      });
      return {
        allowClear: false,
        listHeight: 160,
        showSearch: true,
        placeholder: '请选择设备配置',
        api: getDeviceProfileInfos,
        params: params.value,
        resultField: 'data',
        labelField: 'name',
        valueField: 'id',
        objectToJson: true,
        onSearch: useDebounceFn((e) => {
          params.value.textSearch = e;
        }, 300),
      };
    },
    colProps: {
      span: 12,
    },
    required: true,
  },
  {
    field: 'customer',
    component: 'ApiSelect',
    componentProps: () => {
      const params = ref({
        page: 0,
        pageSize: 50,
        textSearch: '',
      });
      return {
        placeholder: '请选择客户',
        listHeight: 160,
        showSearch: true,
        api: getCustomerList,
        params: params.value,
        resultField: 'data',
        labelField: 'title',
        valueField: 'id.id',
        onSearch: useDebounceFn((e) => {
          params.value.textSearch = e;
        }, 300),
        immediate: true,
      };
    },
    label: '分配给客户',
    colProps: {
      span: 12,
    },
  },
  {
    field: 'isGateway',
    component: 'Switch',
    label: '是否网关',
    colProps: {
      span: 12,
    },
  },
  {
    field: 'isCover',
    component: 'Switch',
    label: '覆盖已连接设备的活动时间',
    colProps: {
      span: 12,
    },
    ifShow: (value) => {
      return value?.model?.isGateway;
    },
  },
  {
    field: 'remark',
    component: 'InputTextArea',
    label: '说明',
    componentProps: {
      placeholder: '请输入说明',
    },
    colProps: {
      span: 24,
    },
  },
];

const TOKENSchemas: FormSchema[] = [
  {
    field: 'token',
    component: 'Input',
    componentProps: () => {
      return {
        placeholder: '请输入访问令牌',
      };
    },
    label: '访问令牌',
    renderComponentContent: ({ values }) => {
      const { setFieldsValue } = tabsFormList[0].Form[1];
      const { clipboardRef } = useCopyToClipboard();
      const { createMessage } = useMessage();
      return {
        suffix: () => {
          return (
            <Button
              size="small"
              type="text"
              onClick={() => {
                if (!values.token || values.token == '') {
                  setFieldsValue({
                    token: generate(20),
                  });
                } else {
                  clipboardRef.value = values.token;
                  createMessage.success('复制成功');
                }
              }}
            >
              <Icon
                icon={values.token ? 'ant-design:copy-outlined' : 'ant-design:sync-outlined'}
              ></Icon>
            </Button>
          );
        },
      };
    },
    colProps: {
      span: 24,
    },
    defaultValue: generate(20),
    required: true,
  },
];
const X509Schemas: FormSchema[] = [
  {
    field: 'certificate',
    component: 'InputTextArea',
    componentProps: {
      placeholder: '请输入PEM 格式的证书',
    },
    label: 'PEM 格式的证书',
    colProps: {
      span: 24,
    },
    required: true,
  },
];
const MQTTschemas: FormSchema[] = [
  {
    field: 'id',
    component: 'Input',
    componentProps: {
      placeholder: '请输入客户端ID',
    },
    label: '客户端ID',
    renderComponentContent: ({ values }) => {
      const { setFieldsValue } = tabsFormList[2].Form[1];
      const { clipboardRef } = useCopyToClipboard();
      const { createMessage } = useMessage();
      return {
        suffix: () => {
          return (
            <Button
              size="small"
              type="text"
              onClick={() => {
                if (!values.id || values.id == '') {
                  setFieldsValue({
                    id: generate(20),
                  });
                } else {
                  clipboardRef.value = values.id;
                  createMessage.success('复制成功');
                }
              }}
            >
              <Icon
                icon={values.id ? 'ant-design:copy-outlined' : 'ant-design:sync-outlined'}
              ></Icon>
            </Button>
          );
        },
      };
    },
    required: true,
  },
  {
    field: 'username',
    component: 'Input',
    componentProps: {
      placeholder: '请输入用户名',
    },
    label: '用户名',
    renderComponentContent: ({ values }) => {
      const { setFieldsValue } = tabsFormList[2].Form[1];
      const { clipboardRef } = useCopyToClipboard();
      const { createMessage } = useMessage();
      return {
        suffix: () => {
          return (
            <Button
              size="small"
              type="text"
              onClick={() => {
                if (!values.username || values.username == '') {
                  setFieldsValue({
                    username: generate(20),
                  });
                } else {
                  clipboardRef.value = values.username;
                  createMessage.success('复制成功');
                }
              }}
            >
              <Icon
                icon={values.username ? 'ant-design:copy-outlined' : 'ant-design:sync-outlined'}
              ></Icon>
            </Button>
          );
        },
      };
    },
    required: true,
  },
  {
    field: 'password',
    component: 'InputPassword',
    componentProps: {
      placeholder: '请输入密码',
    },
    renderComponentContent: ({ values }) => {
      const { setFieldsValue } = tabsFormList[2].Form[1];
      const { clipboardRef } = useCopyToClipboard();
      const { createMessage } = useMessage();
      return {
        suffix: () => {
          return (
            <Button
              size="small"
              type="text"
              onClick={() => {
                if (!values.username || values.username == '') {
                  setFieldsValue({
                    username: generate(20),
                  });
                } else {
                  clipboardRef.value = values.username;
                  createMessage.success('复制成功');
                }
              }}
            >
              <Icon
                icon={values.username ? 'ant-design:copy-outlined' : 'ant-design:sync-outlined'}
              ></Icon>
            </Button>
          );
        },
      };
    },
    label: '密码',
    required: true,
  },
];
const baseFormConfig: Partial<FormProps> = {
  layout: 'vertical',
  showSubmitButton: true,
  showResetButton: false,
  submitButtonOptions: {
    text: '后退',
  },
  actionColOptions: {
    span: 24,
    style: {
      textAlign: 'left',
    },
  },
  ...modalFormStyleSetting,
};

type TabsFormType = {
  key: string;
  tab: string;
  forceRender?: boolean;
  Form: UseFormReturnType;
};

export const tabsFormList: TabsFormType[] = [
  {
    key: 'Access Token',
    tab: 'Access Token',
    forceRender: true,
    Form: useForm(Object.assign({ schemas: TOKENSchemas }, baseFormConfig) as FormProps),
  },
  {
    key: 'X.509',
    tab: 'X.509',
    forceRender: true,
    Form: useForm(Object.assign({ schemas: X509Schemas }, baseFormConfig) as FormProps),
  },
  {
    key: 'MQTT Basic',
    tab: 'MQTT Basic',
    forceRender: true,
    Form: useForm(Object.assign({ schemas: MQTTschemas }, baseFormConfig) as FormProps),
  },
];
